//
//  AppDelegate.swift
//  weile
//
//  Created by LKM on 16/9/23.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import CloudPushSDK
import UserNotifications
import SwiftyJSON


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,UNUserNotificationCenterDelegate,WXApiDelegate{
    
    class func getInstance()->AppDelegate{
        return  ( UIApplication.shared .delegate ) as! AppDelegate ;
    }
    

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //启动图结束后
        
        
        registerAPNS(ap:application);
        initCloudPush();
        // 点击通知将App从关闭状态启动时，将通知打开回执上报
        CloudPushSDK.sendNotificationAck(launchOptions)
        
        LKMLog("======启动咯");
        ActivityRequest.goInitHold(window!);
        
        IQKeyboardManager.sharedManager().enable = true //可以在指定的UIViewController  中动态设置true false（如某个界面不使用 可以在的viewWillAppear viewWillDisappear 中设置 true false）
        IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true //点击背景回收
        IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = "收起"
//        IQKeyboardManager.sharedManager().enableAutoToolbar = false //不显示工具栏
        
        
        
        //--------处理推送数据--------
        let jsonD = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification]
        if(jsonD != nil){
            var json = JSON(jsonD);
        
//            let type:Int = json["wl_c"]["t"].int ?? 0 ;
//            let data:[String:JSON]?=json["wl_c"]["d"].dictionary;
            
            let pe:PushToEntity=PushToEntity.init(json:json);
            
            //得重构，就是初始化数据后.
            Api.LoginAfterRun[Api.NextTaskSerialNumber()] = LoginAfterRunType{ isSuccess in
                //再等2秒，没什么就是要等
                Handler.postDelayed(2, closure: {
                    LKMPushManager.Handel(type: pe.type, data: pe.data)
                })

            }
           
        }
        
        //--------处理推送数据---end-----
        
        WXApi.registerApp("wxa71ab49856c8446b")
        
        
        return true
    }
    
    //------推送--------
    
    func initCloudPush(){
        CloudPushSDK.asyncInit("23479169", appSecret: "07c9729739033bf8626d9c73968bcd8d") { (re:CloudPushCallbackResult?) in
            if (re?.success ?? false) {
                LKMLog("Push SDK init success, deviceId:\(CloudPushSDK.getDeviceId())")
                Api.post_xgtoken(preTaskSerialNumber: nil, deviceId: CloudPushSDK.getDeviceId(), end: { (re:ResponEntity) in
                    //先不鸟任何事
                })
            } else {
                LKMLog("Push SDK init failed, error: \(re?.error )");
            }
        }
        
    }
    
    func registerAPNS(ap: UIApplication){
        if #available(iOS 10.0, *) {
            let _notificationCenter = UNUserNotificationCenter.current()
            setTag(&R.id._notificationCenter, _notificationCenter);
            // 创建category，并注册到通知中心
            createCustomNotificationCategory();
            _notificationCenter.delegate = self;//不处理通知
            // 请求推送权限
            _notificationCenter.requestAuthorization(options: UNAuthorizationOptions.alert.union(UNAuthorizationOptions.badge).union(UNAuthorizationOptions.sound), completionHandler: { (granted:Bool, error:Error?) in
                if (granted) {
                    // granted
                    LKMLog("User authored notification.");
                    // 向APNs注册，获取deviceToken
                    ap.registerForRemoteNotifications();
                } else {
                    // not granted
                    LKMLog("User denied notification.");
                }
            })
            
           
        }else if( Float(UIDevice.current.systemVersion) ?? 0  >= 8.0){
          
            ap.registerUserNotificationSettings(UIUserNotificationSettings(types: UIUserNotificationType.sound.union(.alert).union(.badge), categories: nil) )
            
            ap.registerForRemoteNotifications();

            
        }else {
            // iOS < 8 Notifications
            //UIRemoteNotificationType.alert | UIRemoteNotificationType.badge | UIRemoteNotificationType.sound
            UIApplication.shared.registerForRemoteNotifications(matching: UIRemoteNotificationType.alert )
            
        }
    
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        LKMLog("======anps 失败\(error)")
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
       
        LKMLog("======deviceToken==\(String(data: deviceToken, encoding: String.Encoding.utf8))")
        //会不会CloudPushSDK.asyncInit还没初始化ok？  不怕 demo这样写的 流程不用操心
        CloudPushSDK.registerDevice(deviceToken) { (re:CloudPushCallbackResult?) in
            if (re?.success ?? false) {
                LKMLog("======CloudPushSDK 注册成功")
            }else{
                LKMLog("======CloudPushSDK 注册失败")
            }
        }
    }
    /*
     *  App处于启动状态时，通知打开回调
     处理通知栏点击进来
     */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        
        LKMLog(userInfo);
        
        
        let pe:PushToEntity?=PushToEntity.init(userInfo: userInfo);
        if let p = pe{
                LKMLog("====\(p.type)")
            LKMPushManager.Handel(type: p.type, data: p.data);
        }
//
    }
    
    //---------(iOS 10+)-------
    
    /**
     *  创建并注册通知category(iOS 10+)
     */
    func createCustomNotificationCategory(){
        if #available(iOS 10.0, *) {
            let action1 = UNNotificationAction.init(identifier: "action1", title: "test1", options: UNNotificationActionOptions.foreground)
            let action2 = UNNotificationAction.init(identifier: "action2", title: "test2", options: UNNotificationActionOptions.foreground)
            // 创建id为`test_category`的category，并注册两个action到category
            // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
            let category=UNNotificationCategory.init(identifier: "test_category", actions: [action1,action2], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
            
            let _notificationCenter = getTag(&R.id._notificationCenter) as! UNUserNotificationCenter;
            
            _notificationCenter.setNotificationCategories([category])
        }
    }
    /**
     *  App处于前台时收到通知(iOS 10+)
     */
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        // 通知弹出。这样在前台也能收到通知咯
        completionHandler(UNNotificationPresentationOptions.alert);
        
    }
    
//    @available(iOS 10.0, *)
//    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//        completionHandler();
//    }
    
    
    //------推送---end-----
    
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

